import { ReactElement, useRef, useEffect, useState, RefObject } from 'react'
import { Form, Row, FormInstance, Col, Space, Button } from 'antd'
import Dictionary from '@js/dictionary'
import { awaitWrap } from '@src/assets/js/tool'
import style from './index.module.less'
import { ConditionSchema } from '@src/components/schema/condition'
import { EmployeeSchema } from '@src/components/schema/employeeSchema'
import { FormItems, FormItemSchema } from './map'
import { getPersonList } from './ajax'
import qs from 'query-string'

// 改变搜索条件
function changeSearch (d: { [k: string]: any }, items: FormItemSchema, setParams: (v: {[k: string]: any}) => void): void {
  const keys = Object.keys(items)
  keys.forEach(key => {
    const cc = items[key]
    cc.changeFormat(d)
  })
  setParams(qs.parse(qs.stringify(d)))
}

// 初始化员工列表
async function initPersonList (setPersons: (v: EmployeeSchema[]) => void): Promise<void> {
  const [e, d] = await awaitWrap(getPersonList())
  if (e === null && d instanceof Array) {
    setPersons(d)
  }
}

function initForm (params: {[k: string]: any}, items: FormItemSchema, formRef: RefObject<FormInstance>): void {
  const c = formRef.current
  if (c === null) {
    return undefined
  }
  const r: { [k: string]: any } = {}
  const keys = Object.keys(items)
  keys.forEach(key => {
    const cc = items[key]
    cc.initFormat(params, r)
  })
  c.setFieldsValue(r)
}

interface Props {
  use?: string[]
  unused?: string[]
  otherItems?: FormItemSchema
  params: { [k: string]: any }
  setParams: (v: { [k: string]: any }) => void
}

function Main ({ use, unused, otherItems = {}, params, setParams }: Props): ReactElement {
  const ref = useRef<FormInstance>(null)
  const [items] = useState<FormItemSchema>({ ...FormItems, ...otherItems })
  const [list, setList] = useState<string[]>([])
  const [dictionary, setDictionary] = useState<Dictionary | undefined>()
  const [secretaries, setSecretaries] = useState<EmployeeSchema[]>([])
  useEffect(() => {
    const d = new Dictionary()
    d.init('结案类型,仲裁程序,中止类型')
      .then(() => {
        setDictionary(d)
      })
      .catch(e => console.error(e))
    initPersonList(setSecretaries).catch(e => console.error(e))
  }, [])
  useEffect(() => {
    initForm(params, items, ref)
  }, [ref, params])
  useEffect(() => {
    const keys = Object.keys(items)
    if (use instanceof Array) {
      setList(keys.filter(key => use.includes(key)))
    } else if (unused instanceof Array) {
      setList(keys.filter(key => !unused.includes(key)))
    } else {
      setList(keys)
    }
  }, [use, unused])
  return (
    <div className={style.container}>
      <Form ref={ref} labelCol={{ flex: '152px' }} initialValues={{ tag: '全部', procedure: '全部', processer: '全部', accepter: '全部', closure_type: '全部' }} onFinish={d => changeSearch(d, items, setParams)} onReset={() => ref.current?.submit()}>
        <Row gutter={48}>
          {
            list.map((li, i) => {
              const o = items[li]
              const Component = o.component
              return (
                <Component key={i} dictionary={dictionary} secretaries={secretaries} />
              )
            })
          }
          <Col span={24} className={style.btns}>
            <Space>
              <Button type='primary' htmlType='submit'>查询</Button>
              <Button htmlType='reset'>重置</Button>
            </Space>
          </Col>
        </Row>
      </Form>
    </div>
  )
}

export default Main

export function formatCondition (d: { [k: string]: any }, items: FormItemSchema = FormItems): ConditionSchema[] {
  let r: ConditionSchema[] = []
  const keys = Object.keys(items)
  keys.forEach(key => {
    const o = items[key]
    const c = o.getCondition(d)
    if (c instanceof Array) {
      r = [...r, ...c]
    }
  })
  return r
}
